package com.wtwd.campus.utils;

/**
 * 层级编号工具
 * A01
 * *A01A01
 * .
 * .
 * *A01A98
 * *A01A99-01
 * *A01A99-01A01
 *
 * @author zdl
 * @Description
 * @create 2021-06-09 14:31
 */
public class LevelNoUtitl {
    //每级编号默认长度
    private static int numLength = 2;
    //每级编号默认最大数
    private static int maxNum = 99;
    //每级开始位
    private static char startChar = 'A';
    //每级编号标记
    private static String signChar = "-";
    //起始编号
    private static String startNo = "01";


    public static String getNextNo(String currentCode) {
        int index = currentCode.lastIndexOf(startChar);
        String pNo = currentCode.substring(0, index);
        String currentNo = currentCode.substring(index + 1);
        int currentNum = 0;
        StringBuffer nextNo = new StringBuffer(pNo);
        //序号层级,已分配序号段 A99-01 -> 99-
        String preNo = "";
        int nIndex = currentNo.lastIndexOf(signChar);
        if (nIndex == -1) {//序号未超过最大
            currentNum = Integer.parseInt(currentNo);
        } else {
            currentNum = Integer.parseInt(currentNo.substring(nIndex + 1));
            preNo = currentNo.substring(0, nIndex+1);
        }
        nextNo.append(startChar).append(preNo);
        if (currentNum >= (maxNum - 1)) {//超过最大值
            nextNo.append(maxNum)
                    .append(signChar).append(startNo);
        } else {
            nextNo.append(getNextStrNum(currentNum));
        }
        return nextNo.toString();
    }
    public static String getStartNo(String preNo){
        StringBuffer startNo = new StringBuffer(preNo);
        return startNo.append(startChar).append(LevelNoUtitl.startNo).toString();
    }

    public static void main(String[] args) {
        String[] ss = {"A01", "A01A01", "A01A98", "A01A99-01", "A01A99-98"};
        //String[] ss = {"A01A98", "A01A99-01", "A01A99-98"};
        for (String s : ss) {
            System.out.println(s + "-->" + LevelNoUtitl.getNextNo(s));
        }

    }

    /**
     * 将数字前面位数补零
     *
     * @param num
     * @return
     */
    private static String getStrNum(int num) {
        String s = String.format("%0" + numLength + "d", num);
        return s;
    }

    /**
     * 获取下一个字符编号
     *
     * @param num
     * @return
     */
    private static String getNextStrNum(int num) {
        return getStrNum(++num);
    }

    /**
     * 根据长度获取最大值
     *
     * @param length
     * @return
     */
    private static int getMaxNumByLength(int length) {
        if (length == 0) {
            return 0;
        }
        int maxNum = 1;
        for (int i = 0; i < length; i++) {
            maxNum = maxNum * 10;
        }
        return maxNum - 1;
    }
}
